#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#include "Log.hpp"

#include <unistd.h>



void Usage(const std::string &tip)
{
    std::cout << "Please Use\n\t" << tip << " serverip serverport\n"
              << std::endl;
}

enum
{
    SOCKET_ERROR = 1,
    CONNECT_ERROR,
    USAGE_ERROR
};
int InitClient(std::string &serverip, uint16_t &serverport, struct sockaddr_in *server)
{
    // 1.创建套接字
    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        LOG(FATAL, "socket create error,errno:%d:%s\n", errno, strerror(errno));
        exit(SOCKET_ERROR);
    }
    LOG(INFO,"create socket success\n");
    // 2.客户端要将套接字文件和套接字结构体绑定
    // 由于，套接字结构体的端口号众多，不一定一直归一个进程所拥有
    // 因此，这个绑定过程不能是一对一的，而是随机绑定，这个过程由操作系统来做

    // 本地要向服务器发消息，必须是发送到网络中，即本地看服务器是一个Ip+端口号

    memset(server, 0, sizeof(*server));

    server->sin_family = AF_INET;
    server->sin_port = htons(serverport);
    server->sin_addr.s_addr = inet_addr(serverip.c_str());
    return sockfd;
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(USAGE_ERROR);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    struct sockaddr_in server;
    int sockfd = InitClient(serverip, serverport, &server);
    socklen_t len = sizeof(server);
    
    int n = ::connect(sockfd, (struct sockaddr *)&server, len);
    if (n < 0)
    {
        LOG(FATAL, "connect server error,errno:%d:%s\n", errno, strerror(errno));
        exit(CONNECT_ERROR);
    }

    while (1)
    {
        std::cout << "Please Enter#";
        std::string outstring;
        std::getline(std::cin, outstring);

        ssize_t s = send(sockfd, outstring.c_str(), outstring.size(), 0);

        if (s > 0)
        {
            // 接收逻辑
            char buffer[1024];
            ssize_t m = recv(sockfd, buffer, sizeof(buffer) - 1, 0);
            if (m > 0)
            {
                buffer[m] = 0;
                std::cout << "client receive#" << buffer << std::endl;
            }
            else{
                break;
            }
        }
        else
        {
            break;
        }
    }

    return 0;
}